package coreutil

import (
	"core/corestruct"
	"core/myerrors"
	"fmt"
	"strings"
)

type actionUtil struct {
	allList map[string]corestruct.Action
}

func (p actionUtil) Add(action corestruct.Action) {
	action.FullUrl = strings.ToLower(action.FullUrl)
	if strings.HasSuffix(action.FullUrl, "/") {
		action.FullUrl = action.FullUrl[:len(action.FullUrl)-1]
	}

	var vold, ok = p.allList[action.FullUrl]
	if ok {
		fmt.Println(vold)
		panic(myerrors.New(action.FullUrl + " 已经存在"))
	}

	if "" == action.PinType {
		functionType := action.Value.Method(0).Type()
		numin := action.Value.Method(0).Type().NumIn()
		if numin == 1 {

		} else if numin == 2 {
			paramType := functionType.In(0)
			action.PinType = paramType.String()
			if strings.HasPrefix(action.PinType, "[]") {
				action.PinType = action.PinType[2:]
				action.PinIslist = true
			}

		} else {
			panic(myerrors.New("Action参数只能是1或者2"))
		}
	}

	if "" == action.PoutType {
		functionType := action.Value.Method(0).Type()
		numin := action.Value.Method(0).Type().NumOut()
		if numin == 1 {

		} else if numin == 2 {
			paramType := functionType.Out(0)
			action.PoutType = paramType.String()
			if strings.HasPrefix(action.PinType, "[]") {
				action.PoutType = action.PinType[2:]
				action.PoutIslist = true
			} else if strings.HasSuffix(action.PoutType, "corestruct.Page") {
				action.PoutIspage = true
			}
		} else {
			panic(myerrors.New("Action参数只能是1或者2"))
		}
	}

	p.allList[action.FullUrl] = action
}

// 根据key返回类型
func (p actionUtil) GetAction(url string) *corestruct.Action {
	if tpe, ok := p.allList[url]; ok {
		return &tpe
	}
	return nil
}

// 根据所有action
func (p actionUtil) GetAllAction() map[string]corestruct.Action {
	return p.allList
}

var (
	ActionUtil = &actionUtil{
		allList: make(map[string]corestruct.Action),
	}
)
